import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/user/login.vue'
import home from '@/views/home/home.vue'
import movie from '@/views/movie/movie.vue'
import qa from '@/views/qa/qa.vue'
import user from '@/views/user/user.vue'
import layout from '@/views/user/layout.vue'
import notfound from '@/views/notfound/notfound.vue'
import edit from '@/views/user/edit.vue'

Vue.use(VueRouter)

//配置路由
const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  //配置2级路由
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      {
        name: 'home',
        path: '/home',
        component: home
      },
      {
        name: 'movie',
        path: '/movie',
        component: movie
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        meta: { isLogin: true }
      },
      {
        path: '/',
        redirect: '/home' // 重定向:重新指向其它path,会改变网址: hemo
      }
    ]
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit
  },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  //*代表所以路径 当匹配不到需要的路径就会到重新指向的path */
  {
    path: '*',
    redirect: '/notfound' // 重定向:重新指向其它path,会改变网址: hemo
  }
]
//创建路由实列
const router = new VueRouter({
  routes
})
import { getToken } from '@/utils/token.js'

router.beforeEach((to, from, next) => {
  //console.log(getToken())
  //to去哪里
  // console.log(to)
  //from 从哪里来的
  //console.log(from)
  /*
  next必须写
  next() : 完成守卫(检查)，这个函数必须要调用
    next() : 不传参，让你正常跳转（就是跳转目标路由to）
    next({path:'路由路径'}) ： 进行拦截，不让你走（跳转到我指定路由
*/
  //判断用户有没有登录
  if (to.meta.isLogin && !getToken()) {
    //没有登录，则跳转登录页
    next({ path: '/login' })
  } else {
    //有登录，正常跳转
    next()
  }
})

//导出路由
export default router
